import re
import time
import requests
import uuid
import datetime
from flask import make_response, request, send_from_directory
from flask_restful import abort
from flask_login import current_user, login_user
from funcy import project
from sqlalchemy.orm.exc import NoResultFound
from sqlalchemy.exc import IntegrityError
from funcy import partial
import json
import logging
from redash.utils.dazdata import daz_uname, daz_password
from flask_mail import Message

from redash import models, limiter, mail, settings
from redash.permissions import (
    require_permission,
    require_admin_or_owner,
    is_admin_or_owner,
    require_permission_or_owner,
    require_admin_default,
)
from redash.handlers.base import (
    BaseResource,
    require_fields,
    get_object_or_404,
    paginate,
    order_results as _order_results,
)

from redash.authentication.account import (
    invite_link_for_user,
    send_invite_email,
    send_password_reset_email,
    send_verify_email,
)
from redash.settings import parse_boolean
from redash import settings
from redash.serializers import (
    serialize_data_result_to_xlsx,
)
import sys
import random
from typing import List
from Tea.core import TeaCore

from alibabacloud_dysmsapi20170525.client import Client as Dysmsapi20170525Client
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_dysmsapi20170525 import models as dysmsapi_20170525_models

class ContractsNewResource(BaseResource):
    def get(self):
        result = models.Contracts.get_id()
        return result[0]

    @require_admin_default
    def post(self):
        req = request.get_json(force=True)
        require_fields(req, ("code","name"))

        if not daz_password():
            msg = "请使用正版软件！设备信息：" + daz_uname() + "；许可证：" + settings.DAZ_COMMON
            abort(400, message=msg)

        contracts = models.Contracts(
        id=req["id"],
        org=self.current_org,
        userid=req["userid"],
        bill_date = req["bill_date"],
        employeeid = req["employeeid"],
        departmentid =req["departmentid"],
        code = req["code"],
        name = req["name"],
        type = req["type"],
        contracttype = req["contracttype"],
        party_aid = req["party_aid"],
        party_bid = req["party_bid"],
        party_cid = req["party_cid"],
        pay_direction =req["pay_direction"],
        pricetype =req["pricetype"],
        sign_date = req["sign_date"],
        start_date = req["start_date"],
        end_date = req["end_date"],
        warn_date = req["warn_date"],
        volumepurchase = req["volumepurchase"],
        warn_message = req["warn_message"],
        warn_check = req["warn_check"],
        warn_checkdate = req["warn_checkdate"],
        amount = req["amount"],
        amount_words = req["amount_words"],
        status =req["status"],
        officialcode =req["officialcode"],
        budgetcode =req["budgetcode"],
        templateid=req["templateid"],
        templatecontent =req["templatecontent"],
        message =req["message"],
        sourcetype =req["sourcetype"],
        amounttype =req["amounttype"],
        sourceid =req["sourceid"],
        infrastructure =req["infrastructure"],
        recordcode =req["recordcode"],
        puremployeeid=req["puremployeeid"],
        zhengcai =req["zhengcai"],
        isbulu =req["isbulu"],
        iskeyan=req["iskeyan"],
        iszhaobiao=req["iszhaobiao"],
        empowerperson =req["empowerperson"],
        empowersex =req["empowersex"],
        empowerduties=req["empowerduties"],
        agreementcount=req["agreementcount"],
        warnsealuser=req["warnsealuser"] if "warnsealuser" in req else "",
        )
        contractactivity = models.ContractActivity(
        userid=req["userid"],
        contractsid = req["id"],
        message ="合同新建",
        sourcetype ="contracts",
        sourceid =req["id"],
        )
        try:
            models.db.session.add(contracts)
            models.db.session.add(contractactivity)
            models.db.session.commit()
        except IntegrityError as e:
            if "code" in str(e):
                abort(400, message="编号已存在.")
            abort(500)

        # timeserial.record_event(
        #     {"action": "create", "object_id": timeserial.id, "object_type": "timeserial"}
        # )

class ContractsResource(BaseResource):
    def get(self, contracts_id):
        result = models.Contracts.get_by_id(contracts_id)
        return result.to_dict()

    @require_admin_default
    def post(self, contracts_id):
        req = request.get_json(force=True)
        require_fields(req, ("code","name"))
        if not daz_password():
            msg = "请使用正版软件！设备信息：" + daz_uname() + "；许可证：" + settings.DAZ_COMMON
            abort(400, message=msg)
            
        contracts = models.Contracts.get_by_id(contracts_id)
        params = dict(bill_date=req["bill_date"], employeeid=req["employeeid"], departmentid=req["departmentid"], code=req["code"],
                name=req["name"],type=req["type"],party_aid=req["party_aid"],party_bid=req["party_bid"],party_cid=req["party_cid"],pricetype =req["pricetype"],
                pay_direction=req["pay_direction"],sign_date=req["sign_date"],start_date=req["start_date"],end_date=req["end_date"],amount=req["amount"],
                officialcode=req["officialcode"],budgetcode=req["budgetcode"], templateid=req["templateid"], templatecontent=req["templatecontent"],
                amount_words=req["amount_words"],message=req["message"],amounttype =req["amounttype"],infrastructure =req["infrastructure"],
                recordcode =req["recordcode"],puremployeeid=req["puremployeeid"],warn_date = req["warn_date"],warn_checkdate = req["warn_checkdate"],
                warn_message = req["warn_message"],warn_check = req["warn_check"],volumepurchase = req["volumepurchase"],
                warnsealuser=req["warnsealuser"] if "warnsealuser" in req else "",
                empowerperson =req["empowerperson"],empowersex =req["empowersex"],empowerduties=req["empowerduties"],agreementcount=req["agreementcount"],
                contracttype = req["contracttype"],zhengcai =req["zhengcai"],isbulu =req["isbulu"],iskeyan=req["iskeyan"],iszhaobiao=req["iszhaobiao"])

        try:
            self.update_model(contracts, params)
            models.db.session.commit()
        except IntegrityError as e:
            if "code" in str(e):
                abort(400, message="编号已存在.")
            abort(500)

class ContractsdeleteResource(BaseResource):
    @require_admin_default
    def post(self, contracts_id):
        contracts =  models.Contracts.get_by_id(contracts_id)

        strsql="""delete From  attaches where sourcetype='contracts' and org_id="""+str(self.current_org.id)+""" and sourceid="""+ contracts_id
        models.db.session.execute(strsql)
        strsql="""delete From contractactivity where contractsid="""+ contracts_id
        models.db.session.execute(strsql)
        models.db.session.delete(contracts)
        models.db.session.commit()

class ContractsListResource(BaseResource):
    def post(self):
        req = request.get_json(force=True)
        page = req["page"]
        page_size = req["pagesize"]
        code = req["code"] if "code" in req else ""
        name = req["name"] if "name" in req else ""
        party_a = req["party_a"] if "party_a" in req else ""
        type = req["type"] if "type" in req else ""
        userid = str(req["userid"])
        id = str(req["id"])
        departmentid= req["departmentid"]
        amount = str(req["amount"])
        amountmax = str(req["amountmax"])
        datadown = req["datadown"]
        ifseal = req["ifseal"] if "ifseal" in req else "2"
        isbulu = req["isbulu"] if "isbulu" in req else "5"
        warns = req["warns"] if "warns" in req else "0"
        pricetype = req["pricetype"] if "pricetype" in req else ""
        amounttype = req["amounttype"] if "amounttype" in req else ""
        begindate= req["begindate"] if "begindate" in req else ""
        enddate= req["enddate"] if "enddate" in req else ""
        iszhaobiao = req["iszhaobiao"] if "iszhaobiao" in req else "2"
        beginsign_date= req["beginsign_date"] if "beginsign_date" in req else ""
        endsign_date= req["endsign_date"] if "endsign_date" in req else ""
        beginstart_date= req["beginstart_date"] if "beginstart_date" in req else ""
        endstart_date= req["endstart_date"] if "endstart_date" in req else ""
        beginend_date= req["beginend_date"] if "beginend_date" in req else ""
        endend_date= req["endend_date"] if "endend_date" in req else ""
        stremployeename = req["stremployeename"] if "stremployeename" in req else ""
        order = req["order"] if "order" in req else 1
        orderfield = req["field"] if "field" in req else ""
        if orderfield=="code" :
            orderfield ="t1.code"
        elif orderfield=="officialcode":
            orderfield ="t1.officialcode"
        elif orderfield=="name":
            orderfield ="t1.name"
        elif orderfield=="partyaname":
            orderfield ="t2.strcustomername"
        elif orderfield=="typename":
            orderfield ="t4.typename"
        elif orderfield=="orgname":
            orderfield ="t5.name"
        elif orderfield=="bill_date":
            orderfield ="t1.bill_date"
        elif orderfield=="amount":
            orderfield ="t1.amount"
        elif orderfield=="partybname":
            orderfield ="t3.strcustomername"
        elif orderfield =="staycheck":
            orderfield ="t10.name"
        elif orderfield =="checkdate":
            orderfield ="(case  when t1.status =0 then '' when coalesce(t11.id,0)=0 then COALESCE(to_char(t1.bill_date,'YYYY-MM-DD'),'')  else  COALESCE(to_char(t11.updated_at,'YYYY-MM-DD'),'') end)"
        else:
            orderfield ="t1.bill_date"
            order=1
        

        strwhere ="t1.org_id=" +str(self.current_org.id)
        if code !="" :
            if warns =="2" :
                strwhere = strwhere + " and t1.officialcode like '%"+code+"%'"
            else :
                strwhere = strwhere + " and t1.code like '%"+code+"%'"
        if name !='' :
            strwhere = strwhere + " and t1.name like '%"+name+"%'"
        if stremployeename !='' :
            strwhere = strwhere + " and t6.name like '%"+stremployeename+"%'"
        
        if party_a !='' :
            strwhere = strwhere + " and t2.strcustomername like '%"+party_a+"%'"
        if begindate !='' :
            strwhere = strwhere + " and t1.bill_date >= '"+begindate+"'"
        if enddate !='' :
            strwhere = strwhere + " and to_char(t1.bill_date,'YYYY-MM-DD') <= '"+enddate+"'"
        if type !='' :
            strwhere = strwhere + " and  '"+type+"' = ANY(t1.type)"
        if id>"0" :
            strwhere = strwhere + " and t1.id=" +id
        if len(departmentid)>0 :
            departid=','.join(str(i) for i in departmentid)
            departid='(' + departid +')'
            strwhere = strwhere + " and t1.departmentid in " +departid
        if pricetype == '总价合同':
            strwhere = strwhere + " and t1.pricetype =0 " 
        elif pricetype=="单价合同":
            strwhere = strwhere + " and t1.pricetype =1 "
        elif pricetype=="费率合同":
            strwhere = strwhere + " and t1.pricetype =2 "
        elif pricetype=="成本补偿":
            strwhere = strwhere + " and t1.pricetype =3 "
        elif pricetype=="绩效激励":
            strwhere = strwhere + " and t1.pricetype =4 "
        if amounttype != '':
            strwhere = strwhere + " and '"+amounttype+"'=any(t1.amounttype)" 
        if amount>"0" :
            strwhere = strwhere + " and t1.amount >=" + amount
        if amountmax>"0" :
            strwhere = strwhere + " and t1.amount <=" + amountmax
        if warns =="1" :
            strwhere = strwhere + " and t1.end_date<now()::timestamp + '3 month'"
        if warns =="0" and id=="0" :
            strwhere = strwhere + " and t1.status<>2"
        if warns =="2" and id=="0" :
            strwhere = strwhere + " and t1.status=2"
            if ifseal=="2" :
                strwhere = strwhere + " and t1.id in(select contractsid From contractseal)"
            elif ifseal=="1":
                strwhere = strwhere + " and t1.id not in(select contractsid From contractseal)"
        if isbulu !="5":
            strwhere = strwhere + " and t1.isbulu ="+isbulu
        if iszhaobiao !="2":
            strwhere = strwhere + " and t1.iszhaobiao ="+iszhaobiao
        if beginsign_date !='' :
            strwhere = strwhere + " and t1.sign_date >= '"+beginsign_date+"'"
        if endsign_date !='' :
            strwhere = strwhere + " and to_char(t1.sign_date,'YYYY-MM-DD') <= '"+endsign_date+"'"
        if beginstart_date !='' :
            strwhere = strwhere + " and t1.start_date >= '"+beginstart_date+"'"
        if endstart_date !='' :
            strwhere = strwhere + " and to_char(t1.start_date,'YYYY-MM-DD') <= '"+endstart_date+"'"
        if beginend_date !='' :
            strwhere = strwhere + " and t1.end_date >= '"+beginend_date+"'"
        if endend_date !='' :
            strwhere = strwhere + " and to_char(t1.end_date,'YYYY-MM-DD') <= '"+endend_date+"'"
        if userid !='':
            strwhere = strwhere + """ and  exists(select orgpower_ids from public.users where id='""" + userid + """' 
            and (t1.departmentid=any(orgpower_ids) or 0=any(orgpower_ids)))"""
        strgetfield =""" t1.*,t2.strcustomername as partyaname,COALESCE(t3.strcustomername,'') as partybname,
         array_to_string(t1.contracttype,',') as strcontracttype,array_to_string(t1.amounttype,',') as stramounttype,
        COALESCE(t2.representative,'') as party_representative ,COALESCE(t2.mobile,'') as party_mobile,COALESCE(t2.address,'') as party_address,
        case when t1.status=2 then '已审核' when t1.status=1 then '审核中' else '草稿' end strstatus,t13.name as organizationname,
        t4.typename,t5.name as orgname,t6.name stremployeename,to_char(t1.bill_date,'YYYY年MM月DD日') bill_dateformat,
        case when t1.sourcetype='contractapply' then '合同申请单' when t1.sourcetype='contracts' then (case t1.typeid when 0 then '续签' when 1 then '另签' else '补签' end) else '新建' end as ctype,
        t7.name username ,COALESCE(t3.mobile,'') as partybmobile,COALESCE(to_char(t1.start_date,'YYYY年MM月DD日'),'') as contractstart_date,
        COALESCE(to_char(t1.end_date,'YYYY年MM月DD日'),'') as contractend_date,t8.name as templatename,case when t1.status=2 then '审批结束' else coalesce(t10.name,'待提交') end  as staycheck,
        case  when t1.status =0 then '' when coalesce(t11.billid,0)=0 then COALESCE(to_char(t1.bill_date,'YYYY-MM-DD'),'')  else  COALESCE(to_char(t11.updated_at,'YYYY-MM-DD'),'') end  as checkdate,
        case when contractsealid=0 then '未用印' else '已用印' end as contractseal,
        case when t1.isbulu=0 then '正常' when t1.isbulu=1 then '补录' else '历史备案' end as strbulu, 
        case when t1.iszhaobiao=1 then '是' else '否' end as striszhaobiao, 
        COALESCE(to_char(t1.sign_date,'YYYY年MM月DD日'),'') as contractsign_date,
        case when t1.pricetype=0 then '总价合同' when t1.pricetype=1 then '单价合同'  when t1.pricetype=2 then '费率合同' when t1.pricetype=3 then '成本补偿'  when t1.pricetype=4 then '绩效激励' else '非经济' end as strpricetype,
        (select array_to_string(array_agg(name),',') From users where id =any(CAST(string_to_array(warnsealuser,',') AS integer[]))) as warnsealusername """

        tblname = """public.contracts t1 left join public.customertemp t2 on t1.party_aid=t2.id
                    left join public.customertemp t3 on t1.party_bid=t3.id left join
                    public.contracttypeview t4 on t1.type =t4.type  and t1.org_id=t4.org_id
                    left join public.orgunit t5 on t1.departmentid=t5.id
                    left join public.organizations t13 on t5.org_id=t13.id
                    left join public.users t6 on t1.employeeid= t6.id
                    left join public.users t7 on t1.userid= t7.id
                    left join public.templates t8 on t1.templateid=t8.id 
					left join public.workflow_bill_state t15 on t1.id=t15.billid and t15.bill_enum='contracts' and t15.is_active=true
                    left join public.workflow_state t10 on t15.workflow_stateid=t10.id 
                    left join (select billid,max(updated_at) as updated_at From public.workflow_action where bill_enum='contracts' group by billid) t11 on t1.id=t11.billid """
        #orderfield ="t1.id"
        if not datadown :
            result = models.ContractApply.get_pagequery(tblname,strgetfield,orderfield,page_size,page,order,strwhere)
            return result[0]
        else :
            queryshowfield = models.QueryShowField.get_by_code('contractslist'+ warns)
            ps = queryshowfield.to_dict()
            fieldsshow = ps['fieldsshow']
            fieldsall = json.loads(json.dumps(ps['fieldsall'])) 
            columns =[]
            strsql="select " + strgetfield + " from " + tblname +" where " +strwhere
            strgetfield = ""
            for i in range(len(fieldsall)):
                if fieldsall[i]["key"] in fieldsshow:
                    columns.append({ 'name' : fieldsall[i]["title"]})
                    strgetfield = strgetfield +","+  fieldsall[i]["key"] +" as "+ fieldsall[i]["title"]
                    
            orderfield = req["orderfield"] if "orderfield" in req else "code"
            strsql = "select " + strgetfield[1:] + " from (" + strsql + ") t1 order by "+orderfield
            if order==0 :
                strsql= strsql+" ASC "
            else :
                strsql= strsql+" DESC "
            strsql = """select array_to_json(array_agg(row_to_json(t))) from (""" + strsql + """) t """
            data = models.Contracts.get_selcontracts(strsql)

            article_info = {}
            da1 = json.loads(json.dumps(article_info))
            da1['columns'] = columns #[{"name": "code", "friendly_name": "code", "type": null}, {"name": "name", "friendly_name": "name", "type": null}]
            da1['rows'] = data[0] #[{"code": "code", "name": "name"}, {"code": "code1", "name": "name1"}]

            query_result = da1
            result = serialize_data_result_to_xlsx(query_result,"hetong")
            return send_from_directory(result, "hetong.xlsx",as_attachment=True)

class ContractsActivityResource(BaseResource):
    def get(self, contracts_id,sourcetype):
        result = models.Contracts.getactivity_by_id(contracts_id,sourcetype)
        return result[0]
#     20200718选单
class ContractsSelListResource(BaseResource):
    def post(self):
        req = request.get_json(force=True)
        billtype = req["billtype"]
        billid = str(req["id"])
        strsql ="""select id,code,name,departmentid
                From contracts where org_id=""" +str(self.current_org.id)
        if billtype !='' :
            strsql = """select id,officialcode as code,name,departmentid
                From contracts where org_id=""" +str(self.current_org.id) + """ and status=2 and officialcode !='' """
        if billtype =='contractseal' :
            strsql = strsql + " and id not in(select contractsid from "+billtype+" where id <>"+billid+")"
        if billtype =='contractrecord' :
            strsql = strsql + " and id not in(select contractsid from "+billtype+" where id <>"+billid+")"
        if billtype =='contractstop' :
            strsql = strsql + " and id not in(select contractsid from "+billtype+" where id <>"+billid+")"
        if billtype =='contractfinish' :
            strsql = strsql + " and id not in(select contractsid from "+billtype+" where id <>"+billid+")"

        strsql = """select array_to_json(array_agg(row_to_json(t))) from (""" + strsql + """) t """
        result = models.Contracts.get_selcontracts(strsql)
        return result[0]

#     20201215发送提醒邮件
class ContractsSendmail(BaseResource):
    def post(self):
        req = request.get_json(force=True)
        bill = req["bill"]
        billid = str(req["billid"])
        strsql ="""select t5.name,t6.name stremployeename,t7.name as orgunitname,to_char(t5.bill_date,'YYYY-MM-DD') AS bill_date,t5.amount,t5.message,
            (select string_agg(t2.name,',')
            From public.alert_subscriptions t1 inner join public.notification_destinations t2 on t1.destination_id=t2.id
            where t1.alert_id =(select COALESCE(max(id),0)From alerts where contract_id="""+ billid+""") and t1.isread=false) email,
            (select coalesce(string_agg(t3.mobile,','),'')
            From public.alert_subscriptions t1 inner join public.notification_destinations t2 on t1.destination_id=t2.id
            inner join public.users t3 on t2.user_id=t3.id and length(t3.mobile)=11
            where t1.alert_id =(select COALESCE(max(id),0)From alerts where contract_id="""+ billid+""") and t1.isread=false) mobile,
            (select coalesce(string_agg(t3.code,','),'')
            From public.alert_subscriptions t1 inner join public.notification_destinations t2 on t1.destination_id=t2.id
            inner join public.users t3 on t2.user_id=t3.id
            where t1.alert_id =(select COALESCE(max(id),0)From alerts where contract_id="""+ billid+""") and t1.isread=false) code
            from public.contracts t5 left join  public.users t6 on t5.employeeid=t6.id
            left join public.orgunit t7 on t5.departmentid=t7.id 
            where t5.id="""+ billid
        strsql = """select array_to_json(array_agg(row_to_json(t))) from (""" + strsql + """) t """
        result = models.db.session.execute(strsql).fetchone()
        #======================发送邮件========
        data1 = result[0]
        data2 = data1[0]
        name=data2.get("name")
        stremployeename=data2.get("stremployeename")
        orgunitname=data2.get("orgunitname")
        bill_date=data2.get("bill_date")
        amount=data2.get("amount")
        message=data2.get("message")
        html = """
            <a>合同名称：{name}</a><br />
            <a>经办人：{stremployeename}</a><br />
            <a>经办部门：{orgunitname}</a><br />
            <a>申请时间：{bill_date}</a><br />
            <a>金额：{amount}</a><br />
            <a>备注：{message}</a><br />
            """.format(
                name=name, stremployeename=stremployeename, orgunitname=orgunitname,
                bill_date=bill_date, amount=amount, message=message
            )
        ##=20211023==============================================params=payload #,
        htmltooa = """
            合同名称：{name}
            经办人：{stremployeename}
            经办部门：{orgunitname}
            申请时间：{bill_date}
            金额：{amount}
            备注：{message}
            """.format(
                name=name, stremployeename=stremployeename, orgunitname=orgunitname,
                bill_date=bill_date, amount=amount, message=message
            )
        registerCode ="3001"
        ipport = "192.192.194.236:9611" #"oa.cdlyy.com" # "192.192.194.236:9611"
        userName ="htrest"
        password ="a123456"
        payurl="http://"+ipport+"/seeyon/rest/token/"+userName+"/"+password
       # payload ={'userName':userName,'password':password}
        headers = {"Content-Type": "application/json; charset=UTF-8","Accept": "application/json"}
        try:
            rst = requests.get(
                    payurl, headers=headers
                )
            #rst =rst.text.get_json(force=True)
            jsr= json.loads(rst.text)
            token =jsr["id"]
            if token !="-1" :
                for code in data2.get("code").split(",") :
                    payurl="http://"+ipport+"/seeyon/rest/thirdpartyMessage/receive/singleMessage?token="+token
                    uuidcode=str(uuid.uuid1().int>>64)
                    payload ={'thirdpartyRegisterCode': registerCode,
                        'thirdpartyMessageId': uuidcode,
                        'messageContent': htmltooa,
                        'thirdpartyReceiverId': code,
                        'noneBindingReceiver':  code,
                        'creation_date': datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                        'messageURL': "http://ht.cdlyy.com:10001",
                        'messageH5URL': "http://ht.cdlyy.com:10001"}
                    tests=json.dumps(payload)
                    rst = requests.post(payurl, data=tests, headers=headers)
        except Exception:
            logging.exception("微协同发送错误。")
        ##=======================================================
        recipients = [
            email for email in data2.get("email").split(",") if email
        ]
        if not recipients:
            logging.warning("没有给定电子邮箱，发送已忽略。")

        logging.debug("Notifying: %s", recipients)

        subject = "合同审批提醒"
        try:
            message = Message(recipients=recipients, subject=subject, html=html)
            mail.send(message)
        except Exception:
            logging.exception("邮件发送错误。")
        
        if settings.DAZ_SHORT_MESSAGE_ALERT :
            mobile=data2.get("mobile")
            if len(mobile) >=11 :
                mobilecode = """
                    合同名称："""+ name +""",
                    经办人："""+ stremployeename +""",
                    经办部门："""+ orgunitname +""",
                    申请时间："""+bill_date+""",
                    金额："""+ str(amount) +""",
                    备注："""+ message 

                config = open_api_models.Config(
                    # 您的AccessKey ID,
                    access_key_id=settings.DAZ_ACCESS_KEY_ID,
                    # 您的AccessKey Secret,
                    access_key_secret=settings.DAZ_ACCESS_KEY_SECRET
                )
                # 访问的域名
                config.endpoint =  settings.DAZ_ENDPOINT #'dysmsapi.aliyuncs.com'
                client = Dysmsapi20170525Client(config)
                
                jsonData = '{ "code" : "'+str(mobilecode)+'" }'

                send_sms_request = dysmsapi_20170525_models.SendSmsRequest(
                    phone_numbers=mobile,
                    sign_name=settings.DAZ_SIGN_NAME_ALERT,
                    template_code=settings.DAZ_TEMPLATE_CODE_ALERT,
                    template_param=jsonData
                )
                try:
                    # 复制代码运行请自行打印 API 的返回值
                    callback = client.send_sms(send_sms_request)
                except Exception:
                    logging.exception("短信发送错误。")
        #==============================
        return "ok"